# -*- coding: utf-8 -*-
from django.contrib import auth
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render,render_to_response
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from django.template.context import RequestContext
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.auth.decorators import permission_required

from .models import Choice, Question
from forms import LoginForm
import logging
logger = logging.getLogger("django") # 为loggers中定义的名称

@login_required
def logout(request):
    auth.logout(request)
    return HttpResponseRedirect("/firstapp/login/")

@permission_required('firstapp.index')
@login_required
def logresult(request):
    username = User.objects.get(username=request.user).get_short_name()
    return render(request, 'testLogin/logout.html',{"username":username})


def login(request):
    if request.method == 'GET':
        form = LoginForm()
        return render(request,'testLogin/login.html',{'form':form,})
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            username = request.POST.get('username','')
            password = request.POST.get('password','')
            user = auth.authenticate(username=username,password=password)
            if user is not None and user.is_active:
                auth.login(request,user)
                return HttpResponseRedirect("/firstapp/logresult/")
            else:
                return render(request,'testLogin/login.html',{'form':form,'error':"用户名或密码错误"})
        else:
            return render(request,'testLogin/login.html',{'form':form})

class IndexView(generic.ListView):
    template_name = 'firstapp/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """Return the last five published questions."""
        return Question.objects.order_by('-pub_date')[:5]


class DetailView(generic.DetailView):
    model = Question
    template_name = 'firstapp/detail.html'


class ResultsView(generic.DetailView):
    model = Question
    template_name = 'firstapp/results.html'

def vote(request, question_id):
    p = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'firstapp/detail.html', {
            'question': p,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('firstapp:results', args=(p.id,)))

# Create your views here.
